package com.bytetool.agent.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.util.IOUtils;
import com.bytetool.agent.channel.MessageChannelServer;
import com.bytetool.agent.config.AgentClientConfig;
import com.bytetool.agent.exception.ExceptionUtil;
import com.bytetool.common.entity.PerformanceInfo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @author zouhuixing
 * @date 2024/3/31
 */
public class LoggerConsumer {

    private static String REST_URL;

    static CloseableHttpClient httpClient = HttpClients.createDefault();

    public static void start() {
        init();
        new Thread(() -> {
            while (true) {
                Object message = MessageChannelServer.pull();
                if (message instanceof PerformanceInfo) {
                    PerformanceInfo info = (PerformanceInfo) message;
                    try {
                        sendToServer(info);
                    } catch (Exception e) {
                        ExceptionUtil.handleException(e);
                    }
                    System.out.println(JSON.toJSONString(info));
                }
            }
        }).start();
    }

    private static void init() {
        REST_URL = (String) ((JSONObject) JSON.parse(AgentClientConfig.getConfig())).getOrDefault("url", "");
    }

    private static void sendToServer(PerformanceInfo performanceInfo) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String json = JSON.toJSONString(performanceInfo,config);
        CloseableHttpResponse response = null;
        try {
            //2. 创建post请求
            HttpPost httpPost = new HttpPost(REST_URL);

            //3.设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
            httpPost.setConfig(requestConfig);
            //4.提交参数发送请求
            httpPost.setEntity(new StringEntity(json, ContentType.create("application/json", "utf-8")));
            response = httpClient.execute(httpPost);

            //5.得到响应信息
            int statusCode = response.getStatusLine().getStatusCode();
            //6. 判断响应信息是否正确
            if (HttpStatus.SC_OK != statusCode) {
                //结束请求并抛出异常
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            //7. 转换成实体类
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                String result = EntityUtils.toString(entity, "UTF-8");
                System.out.println(result);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {

        } finally {
            IOUtils.close(response);
        }
    }
}
